Singleton Pattern

2025-02-12

Singletons helps us to work with an instances of a class or object so we have a global state in our application

1. Introduction

Singletons helps us to work with an instances of a class or object so we have a global state in our application

2. Learning Objectives

3. Key Concepts

4. Examples and Practical Cases

let instance;

class DBConnection {
	constructor(uri) {
		if (instance) {
			throw new Error('Only one connection can exist!');
		}
		this.uri = uri;
		instance = this;
	}
	
	connect() {
		this.isConnected = true;
		console.log(`DB ${this.uri} has been connected!`);
	}
	
	disconnect() {
		this.isConnected = false;
		console.log('DB disconnected');
	}
}

const databaseConnector = Object.freeze(new DBConnection());
const connection = databaseConnector;

5. Reflections and Synthesis

6. Conclusion

A final recap and how it connects to your overall learning journey on FrontendMasters.

7. References and Additional Resources

Let's talk

Contact

Have a question or a project in mind? Feel free to reach out.

hello@luisluis.dev